// UI 相关状态管理
class UIManager {
  constructor() {
    this.captureBtn = document.getElementById('captureBtn');
    this.captureFullPageBtn = document.getElementById('captureFullPageBtn');
    this.progressContainer = document.querySelector('.progress-container');
    this.progressCircle = document.querySelector('.progress-circle .progress');
    this.statusText = document.querySelector('.status-text');
  }

  updateProgress(percent, text) {
    const offset = 251.2 * (1 - percent / 100);
    this.progressCircle.style.strokeDashoffset = offset;
    this.statusText.textContent = text;
  }

  resetProgress() {
    this.progressContainer.style.display = 'none';
    this.captureBtn.disabled = false;
    this.captureFullPageBtn.disabled = false;
    this.captureBtn.classList.remove('loading');
    this.captureFullPageBtn.classList.remove('loading');
    this.updateProgress(0, '准备中...');
  }

  setLoading() {
    this.captureBtn.disabled = true;
    this.captureFullPageBtn.disabled = true;
    this.captureBtn.classList.add('loading');
    this.captureFullPageBtn.classList.add('loading');
    this.progressContainer.style.display = 'block';
  }
}

// 截图功能管理
class CaptureManager {
  constructor(uiManager) {
    this.ui = uiManager;
    this.timeoutId = null;
  }

  setTimeoutProtection(duration = 5000) {
    if (this.timeoutId) clearTimeout(this.timeoutId);
    this.timeoutId = setTimeout(() => {
      this.ui.resetProgress();
      alert('截图操作超时，请重试');
    }, duration);
  }

  clearTimeoutProtection() {
    if (this.timeoutId) {
      clearTimeout(this.timeoutId);
      this.timeoutId = null;
    }
  }

  generateFileName(prefix = 'screenshot') {
    const date = new Date();
    const timestamp = date.toISOString().replace(/[:.]/g, '-').slice(0, -5);
    return `${prefix}-${timestamp}.png`;
  }

  async captureTab() {
    const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
    return await chrome.tabs.captureVisibleTab(null, {
      format: 'png',
      quality: 100
    });
  }

  async processImage(dataUrl) {
    const response = await fetch(dataUrl);
    const blob = await response.blob();
    return URL.createObjectURL(blob);
  }

  async saveImage(url, filename) {
    await chrome.downloads.download({
      url: url,
      filename: filename,
      conflictAction: 'uniquify'
    });
  }

  async sendNotification(filename) {
    await chrome.notifications.create({
      type: 'basic',
      iconUrl: '/images/icon128.png',
      title: '截图成功',
      message: `图片已保存为: ${filename}`,
      priority: 2
    });
  }

  handleError(error) {
    console.error('截图错误:', error);
    let errorMessage = '截图失败';

    if (error.message.includes('permission')) {
      errorMessage = '没有截图权限，请确认授权';
    } else if (error.message.includes('network')) {
      errorMessage = '网络错误，请检查连接';
    }

    alert(errorMessage);
  }

  async capture() {
    try {
      this.ui.setLoading();
      this.setTimeoutProtection();

      this.ui.updateProgress(30, '正在截取页面...');
      const dataUrl = await this.captureTab();

      this.ui.updateProgress(60, '正在处理图片...');
      const url = await this.processImage(dataUrl);

      this.ui.updateProgress(90, '正在保存...');
      const filename = this.generateFileName();
      await this.saveImage(url, filename);

      await this.sendNotification(filename);

      this.ui.updateProgress(100, '完成！');
      setTimeout(() => {
        this.ui.resetProgress();
        URL.revokeObjectURL(url);
      }, 1000);

      this.clearTimeoutProtection();
    } catch (error) {
      this.handleError(error);
      this.ui.resetProgress();
      this.clearTimeoutProtection();
    }
  }

  // 滚动截屏功能
  async captureFullPage() {
    try {
      this.ui.setLoading();
      this.setTimeoutProtection(30000); // 滚动截屏需要更长的超时时间

      // 注入内容脚本获取页面信息
      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
      
      // 执行脚本获取页面高度和滚动信息
      const pageInfo = await chrome.scripting.executeScript({
        target: { tabId: tab.id },
        function: () => {
          return {
            scrollHeight: document.documentElement.scrollHeight,
            clientHeight: document.documentElement.clientHeight,
            scrollWidth: document.documentElement.scrollWidth,
            clientWidth: document.documentElement.clientWidth
          };
        }
      });
      
      const { scrollHeight, clientHeight } = pageInfo[0].result;
      const totalSteps = Math.ceil(scrollHeight / (clientHeight * 0.8)); // 每次滚动80%视口高度，确保有重叠
      
      this.ui.updateProgress(10, `准备滚动截屏 (1/${totalSteps})...`);
      
      // 存储每个部分的截图
      const screenshots = [];
      
      // 执行滚动和截图
      for (let i = 0; i < totalSteps; i++) {
        // 滚动到指定位置
        await chrome.scripting.executeScript({
          target: { tabId: tab.id },
          function: (i, clientHeight) => {
            window.scrollTo({
              top: i * clientHeight * 0.8,
              behavior: 'instant'
            });
          },
          args: [i, clientHeight]
        });
        
        // 等待页面渲染
        await new Promise(resolve => setTimeout(resolve, 300));
        
        // 截取当前可见区域
        const dataUrl = await this.captureTab();
        screenshots.push(dataUrl);
        
        // 更新进度
        const progress = Math.min(10 + Math.round(80 * (i + 1) / totalSteps), 90);
        this.ui.updateProgress(progress, `滚动截屏中 (${i+1}/${totalSteps})...`);
      }
      
      this.ui.updateProgress(90, '正在拼接图片...');
      
      // 使用Canvas拼接图片
      const stitchedImageUrl = await this.stitchImages(screenshots, pageInfo[0].result);
      
      // 保存拼接后的图片
      this.ui.updateProgress(95, '正在保存...');
      const filename = this.generateFileName('fullpage');
      await this.saveImage(stitchedImageUrl, filename);
      
      // 发送通知
      await this.sendNotification(filename);
      
      // 完成
      this.ui.updateProgress(100, '完成！');
      setTimeout(() => {
        this.ui.resetProgress();
        URL.revokeObjectURL(stitchedImageUrl);
      }, 1000);
      
      this.clearTimeoutProtection();
      
      // 恢复页面滚动位置
      await chrome.scripting.executeScript({
        target: { tabId: tab.id },
        function: () => {
          window.scrollTo({
            top: 0,
            behavior: 'instant'
          });
        }
      });
      
    } catch (error) {
      this.handleError(error);
      this.ui.resetProgress();
      this.clearTimeoutProtection();
    }
  }
  
  // 拼接多个截图
  async stitchImages(screenshots, pageInfo) {
    return new Promise((resolve) => {
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');
      const { scrollHeight, clientHeight, clientWidth } = pageInfo;
      
      // 设置画布大小
      canvas.width = clientWidth;
      canvas.height = scrollHeight;
      
      let loadedImages = 0;
      const totalImages = screenshots.length;
      const images = [];
      
      // 加载所有图片
      screenshots.forEach((dataUrl, index) => {
        const img = new Image();
        img.onload = () => {
          images[index] = img;
          loadedImages++;
          
          // 所有图片加载完成后拼接
          if (loadedImages === totalImages) {
            // 绘制每个部分到画布
            images.forEach((img, i) => {
              // 计算每个部分的位置，考虑重叠
              const y = Math.floor(i * clientHeight * 0.8);
              ctx.drawImage(img, 0, y, clientWidth, clientHeight);
            });
            
            // 转换为数据URL并返回
            const stitchedImageUrl = canvas.toDataURL('image/png');
            resolve(stitchedImageUrl);
          }
        };
        img.src = dataUrl;
      });
    });
  }
}

// 初始化应用
document.addEventListener('DOMContentLoaded', () => {
  const uiManager = new UIManager();
  const captureManager = new CaptureManager(uiManager);
  
  // 绑定可见区域截图按钮
  uiManager.captureBtn.addEventListener('click', () => {
    captureManager.capture();
  });
  
  // 绑定滚动截屏按钮
  uiManager.captureFullPageBtn.addEventListener('click', () => {
    captureManager.captureFullPage();
  });
});